package com.qttaudio.example;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.pgyersdk.update.PgyUpdateManager;
import com.qttaudio.example.config.Config;
import com.qttaudio.ios.demo.R;
import com.qttaudio.sdk.channel.ChannelEngine;
import com.qttaudio.sdk.channel.ChannelFactory;

import java.io.File;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseAvtivity {

    @BindView(R.id.et_input_phone)
    EditText etInputPhone;
    @BindView(R.id.et_input_roomid)
    EditText etInputRoomid;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.iv_setting)
    ImageView ivSetting;

    private int typeSelectId = R.id.rb_type_voice;
    private int serverIpSelectId = R.id.rb_server_inland;
    private LinkedHashMap<Integer, String> serverIpMap = new LinkedHashMap<Integer, String>() {
        {
            put(R.id.rb_server_inland, "balance.qingspeech.com");
            put(R.id.rb_server_sz, "sz.qingspeech.com");
            put(R.id.rb_server_hk, "hk.qingspeech.com");
            put(R.id.rb_server_singapore, "sg.qingspeech.com");
            put(R.id.rb_server_america, "us.qingspeech.com");
        }
    };

//    private String[] serverIpStrs  = new String[]{};


    // 要申请的权限
    private String[] permissions = {Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private AlertDialog dialog;
    private ChannelEngine channelEngine = null;
    private boolean isJoining = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        SharedPreferences sharedata = getSharedPreferences("data", 0);
        etInputPhone.setText(sharedata.getString("account", ""));
        etInputRoomid.setText(sharedata.getString("roomId", ""));
//        serverIpStrs = serverIpMap.keySet().toArray(serverIpStrs);
        initFile();
        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            for (String permission : permissions) {
                int i = ContextCompat.checkSelfPermission(this, permission);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    showDialogTipUserRequestPermission();
                    break;
                }
            }
        }

        /** 新版本 蒲公英升级**/
        /** 默认方式 **/
        new PgyUpdateManager.Builder()
                .register();
    }

    /**
     * 初始化录音文件目录
     */
    private void initFile() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                File file = new File(Config.record_dir);
                if (!file.exists()) {
                    file.mkdirs();
                }
            }
        }.start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (channelEngine != null) {
            Log.d("qtt_debug", "MainActivity onDestroy");
            channelEngine.delete();
            channelEngine = null;
        }
    }

    @OnClick({R.id.bt_login, R.id.iv_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_setting:
                showDialogSettingIp();
                break;
            case R.id.bt_login:
                if (isJoining) {
                    return;
                }
                isJoining = true;
                String phone = etInputPhone.getText().toString().trim();
                String roomid = etInputRoomid.getText().toString().trim();

                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(LoginActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(roomid)) {
                    Toast.makeText(LoginActivity.this, "房间号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                ChannelFactory.setContext(getApplicationContext());
                ChannelFactory.setAppkey(phone);
                channelEngine = ChannelFactory.GetChannelInstance();

                if (channelEngine == null) {
                    showNormalDialog(ChannelFactory.GetError());
                    isJoining = false;
                    return;
                }

                if (serverIpSelectId > 0) {
                    channelEngine.setServer(serverIpMap.get(serverIpSelectId), 9010,"");
                }

                SharedPreferences.Editor sharedata = getSharedPreferences("data", 0).edit();
                sharedata.putString("account", etInputPhone.getText().toString());
                sharedata.putString("roomId", etInputRoomid.getText().toString());
                sharedata.commit();

                Intent intent = new Intent();
                if(typeSelectId == R.id.rb_type_video){
                    intent.setClass(LoginActivity.this, RoomVideoActivity.class);
                }else {
                    intent.setClass(LoginActivity.this, RoomActivity.class);
                }
                intent.putExtra("roomId", roomid);
                startActivity(intent);
                isJoining = false;
                break;
        }
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {
        new AlertDialog.Builder(this)
                .setTitle("麦克风权限不可用")
                .setMessage("由于该应用需要麦克风，采集音频数据；\n否则，您将无法正常使用该应用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRequestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

//    // 提示用户该请求权限的弹出框
//    private void showDialogSettingIp() {
//        //有右侧选择圆点
//        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("选择服务器");
//        builder.setSingleChoiceItems( serverIpStrs, serverIpSelectId, new DialogInterface.OnClickListener() {
//            public void onClick(DialogInterface dialog, int item) {
//                Log.i("ll","item:"+item+" map："+serverIpMap.get(serverIpStrs[item]));
//                serverIpSelectId = item;
//                dialog.dismiss();
//            }
//        });
//        AlertDialog alert = builder.create();
//        alert.show();
//    }

    /**
     * 设置弹框显示
     */
    private void showDialogSettingIp() {
        //实例化布局
        View view = LayoutInflater.from(this).inflate(R.layout.layout_login_setting_dialog, null);
        //找到并对自定义布局中的控件进行操作的示例
        RadioGroup rg_type = (RadioGroup) view.findViewById(R.id.rg_type);
        RadioGroup rg_servers = (RadioGroup) view.findViewById(R.id.rg_servers);

        if(typeSelectId>0){
            rg_type.check(typeSelectId);
        }
        if(serverIpSelectId>0){
            rg_servers.check(serverIpSelectId);
        }

        rg_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                typeSelectId = checkedId;
            }
        });

        rg_servers.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                serverIpSelectId = checkedId;
            }
        });
        //创建对话框
        AlertDialog dialog = new AlertDialog.Builder(this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create();
        dialog.setView(view);//添加布局
        dialog.show();
    }


    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting() {
        dialog = new AlertDialog.Builder(this)
                .setTitle("麦克风权限不可用")
                .setMessage("请在-应用设置-权限-中，允许该应用使用麦克风权限来获取音频数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void showNormalDialog(String message) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog1 =
                new AlertDialog.Builder(LoginActivity.this);
//        normalDialog1.setIcon(R.drawable.icon_dialog);
        normalDialog1.setTitle(message);
        normalDialog1.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog1.show();
    }

}
